package com.stupidzhe.jdklearning.concurrency.sync;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: StupidZhe
 * @Date: Created in 2017/11/26
 * @Description: wait、notify方法来锁对象解锁对象
 */
public class ObjLockTest {

    public static AtomicInteger atomic = new AtomicInteger(100);

    public static final Object object = new Object();

    public static void main(String[] args) {
        A a = new A();
        B b = new B();
        C c = new C();
        ExecutorService executorService = Executors.newCachedThreadPool();
        executorService.execute(a);
        executorService.execute(b);
        executorService.execute(c);
        executorService.shutdown();
        return;
    }
}

class A implements Runnable {

    @Override
    public void run() {
        synchronized (ObjLockTest.object) {
            while (ObjLockTest.atomic.decrementAndGet() > -1) {
                try {
                    System.out.println("A");
                    ObjLockTest.object.wait();
                    ObjLockTest.object.notifyAll();
//                    System.out.println("A1");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

class B implements Runnable {

    @Override
    public void run() {
        synchronized (ObjLockTest.object) {
            while (ObjLockTest.atomic.decrementAndGet() > -1) {
                try {
                    System.out.println("B");
                    ObjLockTest.object.notifyAll();
                    ObjLockTest.object.wait();
//                    System.out.println("B1");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

class C implements Runnable {

    @Override
    public void run() {
        synchronized (ObjLockTest.object) {
            while (ObjLockTest.atomic.decrementAndGet() > -1) {
                try {
                    System.out.println("C");
                    ObjLockTest.object.wait();
                    ObjLockTest.object.notifyAll();
//                    System.out.println("C1");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}